package com.service.impl;

import com.dao.OrderDao;
import com.dao.OrderItemDao;
import com.dao.impl.OrderDaoImpl;
import com.dao.impl.OrderItemDaoImpl;
import com.pojo.Cart;
import com.pojo.CartItem;
import com.pojo.Order;
import com.pojo.OrderItem;
import com.service.OrderService;

import javax.xml.crypto.Data;
import java.awt.print.Book;
import java.util.Date;
import java.util.Map;

/**
 * @Author hjb
 * @Version 1.0
 * @Contact 1754729389@qq.com
 */
public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();

    @Override
    public String createOrder(Cart cart, Integer userId,String type) {

        //订单号唯一性
        String orderId = System.currentTimeMillis() + "" + userId;
        Order order = new Order(orderId,new Date(),cart.getTotalBasicPrice(),type,userId);
        orderDao.saveOrder(order);

        for (Map.Entry<Integer, CartItem>entry : cart.getItems().entrySet()){
            // 获取每一个购物车中的商品项
            CartItem cartItem = entry.getValue();
            // 转换为每一个订单项
            OrderItem orderItem = null;
            if("deposit".equals(type)) {
                orderItem = new OrderItem(null, cartItem.getName(),cartItem.getDeposit(),orderId);
            }else{
                orderItem = new OrderItem(null, cartItem.getName(),cartItem.getBasicPrice(),orderId);
            }
            // 保存订单项到数据库
            orderItemDao.saveOrderItem(orderItem);
        }
        // 清空购物车
        cart.clear();

        return orderId;


    }
}
